package com.qfmy.service.impl.user;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.qfmy.config.DashScopeConfig;
import com.qfmy.service.user.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * @author 清风明月
 * @Package app.service.impl.user
 * @date 2025/4/30
 * @description 客服
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class CustomerServiceImpl implements CustomerService {

    /**
     * 注入DashscopeConfig
     */
    @Autowired
    private DashScopeConfig dashscopeConfig;


    /**
     * 客服方法，接收用户问题并返回回答
     * @param content 用户问题内容
     * @return 客服回答内容
     */
    public String service(String content) {
        String answer = "";
        try {
            GenerationResult result = callQwenModel(content);
            if (result != null && result.getOutput() != null && result.getOutput().getChoices() != null) {
                answer = result.getOutput().getChoices().get(0).getMessage().getContent();
            }
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            log.error("调用通义千问大模型发生异常", e);
            answer = "抱歉，我暂时无法为您提供回答，请稍后再试。";
        }
        return answer;
    }

    /**
     * 调用通义千问大模型获取回答
     * @param content 用户问题内容
     * @return 模型返回的结果
     * @throws ApiException           当API调用发生错误时
     * @throws NoApiKeyException      当未配置API密钥时
     * @throws InputRequiredException 当输入内容为空时
     */
    @NotNull
    private GenerationResult callQwenModel(String content) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("你是一个智能客服")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(content)
                .build();
        GenerationParam param = GenerationParam.builder()
                .apiKey(dashscopeConfig.getApiKey())
                .model(dashscopeConfig.getCustomerservice())
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        GenerationResult call = gen.call(param);
        return call;
    }
}